/**
 * 开始执行抽奖
 * @param {*} count 抽奖次数 
 */
var run = function (count) {
    //记录累计次数
    usePrizeDrawNum += count;
    //开始抽奖,返回奖品集合
    let items = getItemsByluckDraw(count);
    if (items == null) {
        return;
    }
    //给玩家进行记录抽奖记录
    for (const i in items) {
        let item = items[i];
        //判断是否玩家拥有过
        let flag = false;
        for (const i in playerLotteryRecord) {
            if (item.grade == playerLotteryRecord[i].grade && item.name === playerLotteryRecord[i].name){
                playerLotteryRecord[i].num += item.num;
                playerLotteryRecord[i].count += 1;
                flag = true;
            }
        }
        if (!flag){
            playerLotteryRecord.push({
                grade: item.grade,
                name: item.name,
                num: item.num,
                count: 1
            })
        }
    }
    return items;
}

/**
 * 开始抽奖,返回奖品集合
 * @param {*} count 抽奖次数
 */
let getItemsByluckDraw = function (count) {
    if (count <= 0) {
        alert("抽奖次数有误");
        return null;
    }
    let items = [];
    for (let i = 0; i < count; i++) {
        items.push(getItemByluckDraw());
    }
    return items;
}

/**
 * 开始抽奖,返回奖品集合
 * @param {*} count 抽奖次数
 */
let getItemByluckDraw = function () {
    //将各色礼品珠按照概率放入集合
    let beadArr = [];
    for (const i in jackpotConfig) {
        beadArr.push(jackpotConfig[i].probability);
    }
    //对礼品珠进行抽奖
    let index = random(beadArr);
    let jackpot = jackpotConfig[index].jackpot;
    //将该礼品珠的礼品列表按照概率放入集合
    beadArr = [];
    for (const i in jackpot) {
        beadArr.push(jackpot[i].probability);
    }
    //对礼品中的礼品进行抽奖
    let item;
    let flag = false;
    do {
        item = jackpot[random(beadArr)];
        //查询玩家是否拥有这个物品
        for (const i in playerLotteryRecord) {
            if (playerLotteryRecord[i].name === item.name) {
                flag = true;
            }
        }
    } while (item.haveOne && flag);
    item.grade = index;
    return item;
}


/**
 * 返回命中的索引
 * @param {d} items 概率集合
 */
var random = function (items) {
    let isWhile = false;
    do {
        //当前概率数值
        let num = 0;
        //将item中的百分比概率,转换为1-100000的概率数值
        //新集合
        let newItems = [];
        for (const i in items) {
            let min = num + 1;
            num = (items[i] * 100000) + num;
            newItems.push({ min, max: num })
        }
        //随机数字
        let randomNum = Math.floor(Math.random() * 100000);
        for (const i in newItems) {
            if (newItems[i].min <= randomNum && newItems[i].max >= randomNum) {
                return i;
            }
        }
        isWhile = true;
    } while (isWhile);
};